import datetime
import pandas as pd
import jqdatasdk
from django.core.management.base import BaseCommand
from stocksys import models as stocksys_models


class Command(BaseCommand):
    help = 'create_industry_data_from_jqdata'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('清空行业数据'))
        stocksys_models.Industry.objects.all().delete()
        self.stdout.write(self.style.SUCCESS('验证远程数据密钥'))
        auth_key = None
        with open("data/auth_key.key") as key:
            auth_key = key.read().split(",")
            jqdatasdk.auth(auth_key[0], auth_key[1])
            print(auth_key)
        self.stdout.write(self.style.SUCCESS('请求远程数据'))

        def get_IndustryCategory(abbreviation_name, industry_level):
            data = jqdatasdk.get_industries(abbreviation_name, date=None)
            data['industry_level'] = industry_level
            data['code'] = data.index
            data.index = [x for x in range(len(data))]
            data['abbreviation_name'] = abbreviation_name
            return data

        data = pd.concat([
            get_IndustryCategory('sw_l1', '申万一级行业'),
            get_IndustryCategory('sw_l2', '申万二级行业'),
            get_IndustryCategory('sw_l3', '申万三级行业'),
            get_IndustryCategory('jq_l1', '聚宽一级行业'),
            get_IndustryCategory('jq_l2', '聚宽二级行业'),
            get_IndustryCategory('zjw', '证监会行业'),
        ], axis=0, ignore_index=True)
        # data.to_csv("./data/Industry.csv", index=False)

        self.stdout.write(self.style.SUCCESS('载入行业数据'))
        for index in range(len(data)):
            row = data.loc[index].to_dict()
            stocksys_models.Industry.objects.create(
                name=row['name'],
                code=row['code'],
                industry_level=row['industry_level'],
                start_date=row['start_date'].to_pydatetime(),
                abbreviation_name=row['abbreviation_name']
            )
        self.stdout.write(self.style.SUCCESS('结束载入'))
